var packMonitor_detail = function() {
	var _gatherTime = null;
	var polygon = null;
	var circle_efence = null;
	var overlays = [];
	var circleOverlays=[];
	var efence_type;
	var centerpoints = null;
	return {
		/**
		 * 
		 * @param clientId 终端id
		 * @param packCode 电池唯一序列号
		 * @returns 加载页面
		 */
		init : function(clientId, packCode) {
			monitorDetailCount = 0;
			var d = {};
			d['colClientId'] = clientId;
			d['packCode'] = packCode;
			//根据登录用户是否显示终端信息panel
			packMonitor_detail.showClientInfoPanel();
			setPackInfo(d);
			packMonitor_detail.setEchartData(clientId, packCode);
			//从字典中获取刷新周期
			var cycle = util.getRefreshCycle('REFRESH_CYCLE');
			if(monitorRefreshTimer) {
				window.clearInterval(monitorRefreshTimer);
			}
			//启用页面刷新
			monitorRefreshTimer = window.setInterval(function(){
				//当前激活的tab 根据激活的状态调用指定刷新函数
				packMonitor_detail.showClientInfoPanel();
				setPackInfo(d);
				$(".tab-pane").each(function(){
					if($(this).hasClass("active")){
						switch($(this).attr('id'))
						{
							case "tab_1_1":
								packMonitor_detail.setEchartData(clientId, packCode);
							  break;
							case "tab_1_2":
								packMonitor_detail.setMonitorLocation(clientId, packCode);
							  break;
							case "tab_1_3":
								//需要单独调用方法
								packMonitor_detail.historyLocationRefresh();
								  break;
							case "tab_1_4":
								packMonitor_detail.setHistoryWarning(clientId, packCode, true);
								  break;
							default:
								packMonitor_detail.setEchartData(clientId, packCode);
						}
					}
				});
			}, cycle);
			
			
			
			/**
			 * 配置图表信息
			 * @param d 采集终端ID
			 */
			function setPackInfo(d) {
				App.blockUI($("#packInfoDiv"));//开始loading
				//查询电池详情并赋值
				$.ajax({
					"type" : "post",
					"url" : "main/packDataMonitor/getPackDataDetail.mvc",
					"dataType" : "json",
					"cache":false,
					"async":true,
					"data" : d,
					"success" : function(resp) {
						//debugger
						if(resp.packInfo != null){
							/*if(resp.packInfo.POWER_ON_STATUS == "下电"){
								App.unblockUI($("#packInfoDiv"));//停止loading
								util.showModal("#_powerFail", "电池已下电，请检查电池状态！");
								window.clearInterval(monitorRefreshTimer);
								return false;
							}*/
							_gatherTime = resp.packInfo.GATHER_TIME;
							//处理详情
							var _packInfo = resp.packInfo;
							$("#NETWORK_STANDARD").text(resp.packInfo.NETWORK_STANDARD);
							$("#CARRIER").text(resp.packInfo.CARRIER);
							$("#SIM_PHONENO").text(resp.packInfo.SIM_PHONENO);
							$("#GPS_SIG").text(resp.packInfo.GPS_SIG);
							$("#GPRS_SIG").text(resp.packInfo.GPRS_SIG);

							//加载gps,gprs动画
							var gps = $('#gps');
							var gpsNum = $('#gpsNum');
							var gprs = $('#gprs');
							var gprsNum = $('#gprsNum');
							gps.text(resp.packInfo.GPS_SIG);
							gpsNum.animate({width: (resp.packInfo.GPS_SIG)*48/15},1000);
							gprs.text(resp.packInfo.GPRS_SIG);
							gprsNum.animate({width: resp.packInfo.GPRS_SIG*48/35},1000);

							//packMonitor_detail.setSign("div_gps_sign", Math.ceil((parseInt(resp.packInfo.GPS_SIG) + 1)/3));
							//packMonitor_detail.setSign("div_gprs_sign", Math.ceil(parseInt(resp.packInfo.GPRS_SIG)/7));
							
							$("#PACK_CODE").text(resp.packInfo.PACK_CODE);
							$("#GATHER_TIME").text(resp.packInfo.GATHER_TIME);
							$("#RUN_TIME_SPAN").text(resp.packInfo.RUN_TIME_SPAN);
							$("#FAC_NAME").text(resp.packInfo.FAC_NAME);
							
							$("#EL_VOL").text(resp.packInfo.EL_VOL);
							$("#EL_CURRENT").text(resp.packInfo.EL_CURRENT);
							//packMonitor_detail.setSocCanvas(resp.packInfo.SOC);
							//
							var  batteryCapacity = $('#battery-capacity');
							batteryCapacity.animate({height: resp.packInfo.SOC*190/100},1000);
							batteryCapacity.find('span').text(resp.packInfo.SOC+"%");

							$("#SOC").text(resp.packInfo.SOC+"%");
							$("#MAX_VOL_VAL").text(resp.packInfo.MAX_VOL_VAL);
							$("#MIN_VOL_VAL").text(resp.packInfo.MIN_VOL_VAL);
							$("#MAX_TEMP_VAL").text(resp.packInfo.MAX_TEMP_VAL);
							packMonitor_detail.setTempCanvas("chart", (resp.packInfo.MAX_TEMP_VAL).substring(0, (resp.packInfo.MAX_TEMP_VAL).length -3));
							//packMonitor_detail.updateEchart((resp.packInfo.MAX_TEMP_VAL).substring(0, (resp.packInfo.MAX_TEMP_VAL).length -3));
							$("#MIN_TEMP_VAL").text(resp.packInfo.MIN_TEMP_VAL);
							$("#MIN_TEMP_VAL").text(resp.packInfo.MIN_TEMP_VAL);
							$("#POWER_ON_STATUS").text(resp.packInfo.POWER_ON_STATUS);
							if(resp.packInfo.RUN_STATUS == '0') {

                                $("#RUN_STATUS").text("是");
                            } else {
                                $("#RUN_STATUS").text("否");
							}

							/*
							 * 终端信息
							 */
							$("#CUS_NAME").text(resp.packInfo.CUS_NAME);
							$("#COL_CLIENT_ID").text(resp.packInfo.COL_CLIENT_ID);
							$("#IMSI").text(resp.packInfo.IMSI);
							$("#GPS_NUM").text(resp.packInfo.GPS_NUM);
							$("#PACK_MODEL").text(resp.packInfo.PACK_MODEL);
							$("#ADDRESS").text(resp.packInfo.ADDRESS);
							$("#SIM_ICCID").text(resp.packInfo.SIM_ICCID);


							
							
							//未关联厂区提示
							if(_packInfo.FAC_NAME==undefined){
								$("#FAC_NAME").text("尚未关联厂区").css({
									"color": "red"
								});
								

							}
						}
						App.unblockUI($("#packInfoDiv"));//停止loading
					},
					error:function(e){
						App.unblockUI($("#packInfoDiv"));//停止loading
						rmsBox.notify('error', {msg: '出错了！', delay:3000});
					}
				});
			}

			//切换tab echart
			$('.nav-tabs a[href="#tab_1_1"]').on('shown.bs.tab', function(e){
				setPackInfo(clientId, packCode);
			});
			//切换tab 位置监控
			$('.nav-tabs a[href="#tab_1_2"]').on('shown.bs.tab', function(e){
				packMonitor_detail.setMonitorLocation(clientId, packCode);
			});
			
			//切换tab 位置历史
			$('.nav-tabs a[href="#tab_1_3"]').on('shown.bs.tab', function(e){
				//首先销毁当前页面table数据
				$('#history_location_table').DataTable().destroy();
				packMonitor_detail.setHistoryLocation(clientId, packCode);
			});
			
			//切换tab 历史监控
			$('.nav-tabs a[href="#tab_1_4"]').on('shown.bs.tab', function(e){
				//首先销毁当前页面table数据
				$('#history_warning_table').DataTable().destroy();
				packMonitor_detail.setHistoryWarning(clientId, packCode,false);
			});
			
			//切换tab 页面跳转
			$('.nav-tabs a[href="#tab_1_5"]').on('shown.bs.tab', function(e){
				util.showContent('pages/system/historyBoard.jsp',{'packCode':packCode})
			});
			
			//切换tab 电子围栏
			$('.nav-tabs a[href="#tab_1_6"]').on('shown.bs.tab', function(e){
				e.preventDefault();
				packMonitor_detail.setEfence(clientId, packCode,'');
			});
			
			$("#pwoerFail_confirm_button").on("click", function(){
				util.showContent('pages/monitor/packDataMonitor.jsp');
			})
			
			//重绘多边形
			$("#ploygon_redraw").on("click",function(e){
				e.preventDefault();
				packMonitor_detail.setEfence(clientId, packCode,'1');
			})

			//重绘圆形
			$("#circle_draw").on("click",function(e){
				e.preventDefault();
				packMonitor_detail.setEfence(clientId, packCode,'0');
			})

			$("#ploygon_save").on("click", function(e){
				e.preventDefault();
				var data = [];
				if(efence_type == '0') {
					for(var i = 0; i < circleOverlays.length; i++){  
			            var circles = circleOverlays[i];  
			            var o = {};
			            o.lon = circles.getCenter().lng;
			            o.lat = circles.getCenter().lat;
			            o.colClientId = clientId;
		                o.packCode = packCode;
		                o.type = '0';
		                o.radius = circles.getRadius();
		                data.push(o);
	            	}
		        }else if(efence_type == '1') {
		        	for(var i = 0; i < overlays.length; i++){  
			            var overlay=overlays[i].getPath();  
			            for(var j = 0; j < overlay.length; j++){  
			                var o= {};
			                o.lon = overlay[j].lng;
			                o.lat = overlay[j].lat;
			                o.colClientId = clientId;
			                o.packCode = packCode;
			                o.no = j;
			                o.type = '1';
			                data.push(o);
			            } 
		        	}  
		        }
					        
		    	$.ajax({
					'type':'post',
					'url':'main/packDataMonitor/saveEfenceInfo.mvc',
					'dataType':'json',
					"cache":false,
					'async':false,
					'data':{data:JSON.stringify(data)
						},
					'success':function(data){
						$("#tips_msg").text("保存成功！");
						setTimeout(function(){
							$("#tips_msg").text("");
						}, 1000);
					},
					'error':function(msg){
						console.log("error");
					}
				})
			})
			
			
			$("#ploygon_check").on("click", function(){
				var result;
				if(!centerPoints){
					$("#tips_msg").text("未找到车辆定位信息!");
					setTimeout(function(){
						$("#tips_msg").text("");
					}, 5000);
					return;
				}
				if(efence_type == '1') {
					result=BMapLib.GeoUtils.isPointInPolygon(centerPoints, polygon);
				} else if(efence_type == '0') {
					result=BMapLib.GeoUtils.isPointInCircle(centerPoints,circle_efence);
				}
				
				if(result){
					$("#tips_msg").text("车辆在区域内!");
				} else{
					$("#tips_msg").text("车辆不在区域内");
				}
				setTimeout(function(){
					$("#tips_msg").text("");
				}, 5000);
			})
			
		},

		
		
		/**
		 * 加载echart图表数据
		 * @param c 终端id 
		 * @param p 电池唯一序列号
		 * @returns
		 */
		setEchartData:function(c, p){
			var _maxVol = $("#MAX_VOL_VAL").text();
			_maxVol = _maxVol.substring(0, _maxVol.length-3);
			var _minVol = $("#MIN_VOL_VAL").text();
			_minVol = _minVol.substring(0, _minVol.length-3);
			if(_maxVol){
			$.ajax({
				"type" : "post",
				"url" : "main/packDataMonitor/getEchartData.mvc",
				"dataType" : "json",
				"cache":false,
				"async":true,
				"data" : {
					"clientId": c,
					"packCode": p,
					"maxVol": _maxVol,
					"minVol": _minVol
				},
				"success" : function(resp) {
					var markPoint;
					var colorList;
					$("#minitor_pack_chart").empty();
					if(resp.chartInfo != null){
						//处理表格
						$.each(resp.chartInfo, function(i, item){
							//温度
							var temp = "";
							$.each(item.temp,function(k, te){
								temp += te.temp+"、";
							})
							if(temp){
								temp = temp.substring(0,temp.length-1);
							}
							//动态创建表格
							var chartHtml = "";
							chartHtml += '<li> <div class="echarts-title"> ';
							chartHtml += '<span class = "c-bold">第'+item.no+'组</span>';
							chartHtml += '&nbsp;&nbsp;&nbsp;温度监测点单体序号/温度(℃)：';
							chartHtml += '<span class="c-red">'+temp+'</span>';
							chartHtml += '</div>';
							if(item.vol){
								chartHtml += '<div id="chart_'+i+'"class="echats"></div>';
							}
							$("#minitor_pack_chart").append(chartHtml);
							//调用echart
							if(item.vol){
								// item.markpoint 峰值标志位 11：高压报警&&低压报警 10：高压报警 01：低压报警 00：没有报警
								/*if ("11"==item.markpoint) {
									//既有高压报警 又有低压报警
									markPoint = [{
											type : 'max',
											name : '最大值',
											itemStyle : {
												normal : {
													color : '#000'
												}
											}
										}, {
											type : 'min',
											name : '最小值',
											itemStyle : {
												normal : {
													color : '#000'
												}
											}
										}
									];
									colorList = ['#E02222', '#FFFF00', '#57B5E3'];
								} else if ("10"==item.markpoint) {
									//只有高压报警
									markPoint = [{
											type : 'max',
											name : '最大值',
											itemStyle : {
												normal : {
													color : '#000'
												}
											}
										}
									];
									colorList = ['#E02222', '#57B5E3', '#57B5E3'];
								} else if ("01"==item.markpoint) {
									//只有低压报警
									markPoint = [{
											type : 'min',
											name : '最小值',
											itemStyle : {
												normal : {
													color : '#000'
												}
											}
										}
									];
									colorList = ['#57B5E3', '#FFFF00', '#57B5E3'];
								} else {
									//不存在告警
									markPoint = null;
									colorList = ['#57B5E3', '#57B5E3', '#57B5E3']
								}*/
								markPoint = [{
									type: 'max',
									name: '最大值',
									itemStyle: {
										normal: {
											color: '#E02222'
										}
									}
								}, {
									type: 'min',
									name: '最小值',
									itemStyle: {
										normal: {
											color: '#000',
										}
									}
								}];
								colorList = ['#E02222', '#FFFF00', '#57B5E3'];
								//如果存在电压报警 该组中存在对应的电压值 启用对应的m c;
								packMonitor_detail.EconfigAPI(item,"chart_"+i, markPoint, colorList);
							}
						})
					}
					App.unblockUI($("#packInfoDiv"));//停止loading
				},
				error:function(e){
					App.unblockUI($("#packInfoDiv"));//停止loading
					rmsBox.notify('error', {msg: '出错了！',delay:3000});
				}
			});
		  } else {
			  $("#minitor_pack_chart").empty();
		  }
		},
		/**
		 * 历史报警处理
		 * @param c 终端id
		 * @param p 电池id
		 * @param isQuery 是否刷新
		 */
		setHistoryWarning:function(c, p, isQuery) {
			if (isQuery) {
				//自动刷新时只重新加载当前页数据
				var table = $('#history_warning_table').DataTable();
				table.draw(false);
				return;
			}
			var tableId = 'history_warning_table';
			util.initCheckBox(tableId);
			var checkBoxDivStr = '<div class="checker" onclick="util.selectCheckBox(\'' + tableId + '\', this)"><span><input type="checkbox" class="checkboxes"></span></div>';			
			//table查询方法
			function queryData(sSource, aoData, fnCallback) {
				aoData.push({
					"name" : "clientId",
					"value" : c
				});
				aoData.push({
					"name" : "packCode",
					"value" : p
				});
				aoData.push({
					"name" : "isCurrent",
					"value" : true
				});
				$.ajax({
					"type" : "get",
					"contentType" : "application/json",
					"url" : sSource,
					"dataType" : "json",
					"data" : {
						"aoData" : JSON.stringify(aoData)
					},
					"success" : function(resp) {
						fnCallback(resp);
					}
				});
			};
	         //处理表格
			$('#history_warning_table').DataTable({
				"bInfo": true,//页脚信息
				"bDestroy": true,
				"bRetrieve": true,
				"processing" : false,
				"serverSide" : true,
				"pageLength" : 10,
				"oLanguage" : util.getDToLanguage(),
				"sAjaxSource" : "main/packDataMonitor/getHistoryWarningList.mvc",
				"fnServerData" : queryData,
				"sDom" : "<'row-fluid'r>t<'row-fluid'<'span6'i><'span6'p>>",
				"columns" : [
					{
						"data" : "pkId",
						"render" : function(data, type, full, meta) {
							 return checkBoxDivStr;
						},
						"bSortable" : false
					},
					{
						"data" : "handleStatus",
						"bSortable" : false,
						"defaultContent": "",
						"render" : function(data,type,full,meta) {
							if("已处理"==data){
								return "<span class=\"label\">"+data+"</span>";
							}else if("未处理"==data){
								return "<span class=\"label label-important\">"+data+"</span>";
							} else if ("无需处理"==data) {
								return "<span class=\"label label-warning\">"+data+"</span>";
							}
						}
					},
					{
						"data" : "alertCategory",
						"bSortable" : false,
						"defaultContent": ""
					},
					{
						"data" : "happenTime",
						"bSortable" : false,
						"defaultContent": "",
						"render" : function(data, type, full, meta) {
							if(data){
							   return util.getDateStr(data);
							}
						}
					},
					{
						"data" : "alertCode",
						"bSortable" : false,
						"defaultContent": ""
					},
					{
						"data" : "updateDate",
						"bSortable" : false,
						"defaultContent": "",
						"render" : function(data, type, full, meta) {
							if(data){
							   return util.getDateStr(data);
							}
						}
					},
					{
						"data" : "",
						"bSortable" : false,
						"render" : function(data, type, full, meta) {
							if(full.zipOrigmsgPath) {
								return "<a href='javascript:;' onclick='packMonitor_detail.downloadDatagram(\"" + full.pkId + "\")' class='c-blue c-line'>下载报文</a>";
							} else if (full.handleStatus=='未处理') {
								return "<a href='javascript:;' onclick='packMonitor_detail.dataBack(\"" + full.pkId + "\")' class='c-blue c-line'>数据回传</a>";
							}
						},
						"defaultContent": ""
					}
				],
				"fnDrawCallback" : function(oSetting) {
					util.clearSelected(tableId);
				}
			});
			$("table#history_warning_table").find("th").eq(0).addClass("sorting_asc_disabled");
			
			//清除按钮绑定样式
			$('#set_handled, #set_unneed_handled').off("click");
			$("#_confirmModal").off( "click", "#set_handled_conf");
			$("#_confirmModal").off( "click", "#set_unneed_conf");
			//点击标记处理
			$("#set_handled").click(function(e){
				var d = [];
				d = util.getCheckedData("history_warning_table");
				if (d.length ==0 ) {
					util.showModal("#_alertModal", "请选择要操作的记录！");
					return false;
				} else {
					//检查所选择数据状态
					var idArray=[];
					for (var i=0;i<d.length;i++) {
						idArray.push(d[i].pkId);
					}
					$.ajax({
						"type" : "post",
						"url" : "main/packDataMonitor/checkUnhandled.mvc",
						"dataType" : "json",
						"async":false,
						"data" : {
							"ids" : idArray.join(",")
						},
						"success" : function(resp) {
							if (resp == true) {
								util.showModal("#_confirmModal", "你确定要标记已处理？", "set_handled_conf");
							} else {
								util.showModal("#_alertModal", "所选记录包含已处理或数据未回传的记录，请重新选择！");
							}
						}
					});
				}
			});
			
			//置为已处理
			$("#_confirmModal").on('click', '#set_handled_conf', function() {
				var d = [];
				d = util.getCheckedData("history_warning_table");
				var idArray = new Array();
				for (var i = 0;i<d.length;i++) {
					idArray.push(d[i].pkId);
				}
				$.ajax({
					"type" : "post",
					"url" : "main/packDataMonitor/setAlertHandled.mvc",
					"dataType" : "json",
					"data" : {
						"ids" : idArray.join(","),
						"handleType" : "handled"
					},
					"success" : function(resp) {
						if (resp.msg==true) {
							rmsBox.notify('success', {msg: '操作成功！'});
							var table = $('#history_warning_table').DataTable();
							table.draw(true);
						} else {
							rmsBox.notify('error', {msg: '数据异常！'});
						}
					},
					"error" : function() {
						rmsBox.notify('error', {msg: '数据异常！'});
					}
				});
			});
			
			//点击无需处理
			$("#set_unneed_handled").click(function(e) {
				var d = [];
				d = util.getCheckedData("history_warning_table");
				if (d.length ==0 ) {
					util.showModal("#_alertModal", "请选择要操作的记录！");
					return false;
				} else {
					//检查所选择数据状态
					var d = [];
					d = util.getCheckedData("history_warning_table");
					var idArray=[];
					for (var i=0;i<d.length;i++) {
						idArray.push(d[i].pkId);
					}
					$.ajax({
						"type" : "post",
						"url" : "main/packDataMonitor/checkUnneedhandled.mvc",
						"dataType" : "json",
						"async":false,
						"data" : {
							"ids" : idArray.join(",")
						},
						"success" : function(resp) {
							if(resp==true){
								util.showModal("#_confirmModal", "你确定要置为无需处理？", "set_unneed_conf");
							}else{
								util.showModal("#_alertModal", "所选记录包含已处理或数据已回传的记录，请重新选择！");
							}
						}
					});
				}
			});
			
			//置为无需处理
			$("#_confirmModal").on('click', '#set_unneed_conf', function() {
				var d = [];
				d = util.getCheckedData("history_warning_table");
				var packIds = new Array();
				for (var i = 0;i<d.length;i++) {
					packIds.push(d[i].pkId);
				}
				$.ajax({
					"type" : "post",
					"url" : "main/packDataMonitor/setAlertHandled.mvc",
					"dataType" : "json",
					"data" : {
						"ids" : packIds.join(","),
						"handleType" : "unneed"
					},
					"success" : function(resp) {
						if (resp.msg==true) {
							rmsBox.notify('success', {msg: '操作成功！'});
							var table = $('#history_warning_table').DataTable();
							table.draw(true);
						} else {
							rmsBox.notify('error', {msg: '数据异常！'});
						}
					},
					"error" : function() {
						rmsBox.notify('error', {msg: '数据异常！'});
					}
				});
			});
		},
		
		/**
		 * 刷新历史轨迹tab
		 * @returns
		 */
		historyLocationRefresh:function(){
			$('#history_location_table').DataTable().draw(true);
		},
		/**
		 * 显示历史位置信息
		 * @param c 终端id
		 * @param p 电池id
		 */
		setHistoryLocation:function(c, p){
			//导出数据
		  $("#locaion_history_box").empty();//清空地图内容
			    var map = new BMap.Map("locaion_history_box");
				map.centerAndZoom(new BMap.Point(116.417854,39.921988),5);//默认中心点
				map.enableScrollWheelZoom(true);//缩放
				//向地图中添加缩放控件  
          //向地图中添加缩略图控件  
          var ctrlOve = new window.BMap.OverviewMapControl({  
              anchor: BMAP_ANCHOR_BOTTOM_RIGHT,  
              isOpen: 1  
          });  
          map.addControl(ctrlOve);
          //向地图中添加比例尺控件  
          var ctrlSca = new window.BMap.ScaleControl({  
              anchor: BMAP_ANCHOR_BOTTOM_LEFT  
          });  
          map.addControl(ctrlSca); 
          var start_circle = new BMap.Symbol(BMap_Symbol_SHAPE_CIRCLE, {
			    scale: 5.0,
			    strokeWeight: 1.5,
			    fillColor: 'blue',
			    fillOpacity: 1.0
       });
          var circle = new BMap.Symbol(BMap_Symbol_SHAPE_CIRCLE, {
			    scale: 5.0,
			    strokeWeight: 1.5,
			    fillColor: 'red',
			    fillOpacity: 1.0
         });
          $.ajax({
				"type" : "post",
				"url" : "main/packDataMonitor/getHistoryLocationList.mvc",
				"dataType" : "json",
				"async" : true,
				"data" : {
					'clientId' : c,
					'packCode' : p,
					'gatherTimes' : _gatherTime,
					'selectTime' : null,
					'flag':'current'
					
				},
				"success" : function(resp) {
					if(resp.aaData.length>0){
						//存在数据添加导出按钮
						var points = new Array();
						for(var i = 0; i < resp.aaData.length; i++){
							points.push(new BMap.Point(parseFloat(resp.aaData[i].longitude),parseFloat(resp.aaData[i].latitude)));
							if(i == 0){
								var marker = new BMap.Marker(new BMap.Point(parseFloat(resp.aaData[i].longitude),parseFloat(resp.aaData[i].latitude)), {icon: circle});
								map.addOverlay(marker);
							}
							if( i == (resp.aaData.length - 1)){
								var marker = new BMap.Marker(new BMap.Point(parseFloat(resp.aaData[i].longitude),parseFloat(resp.aaData[i].latitude)), {icon: start_circle});
								map.addOverlay(marker);
							}
						}
						var polyline = new BMap.Polyline(
														   points, 
								                         { strokeColor:"green",//设置颜色   
				                                           strokeWeight:3, //宽度  
				                                           strokeOpacity:1
				                                           }
						                                 );//透明度  
				              map.addOverlay(polyline);  
			  	    //缩放级别自适应
					var view = map.getViewport(eval(points));  
					var mapZoom = view.zoom;   
					var centerPoint = view.center;   
					map.centerAndZoom(centerPoint,mapZoom);  
					}else {
						//清空轨迹
						map.clearOverlays();
					}
				},
				error:function(e){
					App.unblockUI($("#packInfoDiv"));//停止loading
					rmsBox.notify('error', {msg: '加载数据出错！'});
				}
			});
          
            //处理表格
			$('#history_location_table').DataTable({
				"searching": false,
				"bDestroy": true,
				"bRetrieve": true,
				"processing" : true,
				"serverSide" : true,
				"sAjaxSource" : "main/packDataMonitor/getHistoryLocationListByPage.mvc",
				"fnServerData" : queryData,
				"pageLength" : 10,
				"sDom" : "<'row-fluid'r>t<'row-fluid'<'span6'i><'span6'p>>",
				"oLanguage" : util.getDToLanguage(),
				"columns" : [ 
				/*{
					"data" : "",
					"bSortable" : false,
					"visible" : false,  //隐藏列
					"defaultContent": ""
				},*/
				{
					"data" : "gatherTime",
					"bSortable" : false,
					"defaultContent": ""
				},
				{
					"data" : "address",
					"bSortable" : false,
					"defaultContent": ""
				}
			 ]
			});
			//table查询方法
			function queryData(sSource, aoData, fnCallback) {
				aoData.push({
					"name" : "clientId",
					"value" : c
				});
				aoData.push({
					"name" : "packCode",
					"value" : p
				});
				aoData.push({
					"name" : "gatherTimes",
					"value" : _gatherTime
				});
				aoData.push({
					"name" : "flag",
					"value" : 'current'
				});
				$.ajax({
					"type" : "get",
					"contentType" : "application/json",
					"url" : sSource,
					"dataType" : "json",
					"data" : {
						"aoData" : JSON.stringify(aoData)
					},
					"success" : function(resp) {
						//绘制历史轨迹    resp.aaData
						if(resp.aaData.length>0){
							//存在数据添加导出按钮
							$("#history_toolbar").show();
						}else {
							//没有数据   移除导出按钮
							$("#history_toolbar").hide();
							//清空轨迹
						}
						fnCallback(resp);
					}
				});
			};
			
			 //导出数据
	  	    $('#export_history').on('click',function(){
	  			Date.prototype.Format = function (fmt) { //author: meizz 
				    var o = {
				        "M+": this.getMonth() + 1, //月份 
				        "d+": this.getDate(), //日 
				        "h+": this.getHours(), //小时 
				        "m+": this.getMinutes(), //分 
				        "s+": this.getSeconds(), //秒 
				        "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
				        "S": this.getMilliseconds() //毫秒 
				    };
				    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
				    for (var k in o)
				    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
				    return fmt;
				};
				var exportTime = new Date().Format("yyyyMMddhhmmss");
	  	    	var url = "main/packDataMonitor/getHistoryLocationListForTrail.mvc?clientId="+c+"&packCode="+p+"&gatherTimes="+_gatherTime + "&exportTime="+ exportTime;
	  	    	$.fileDownload(url, {
	    			httpMethod: 'POST',
	    			prepareCallback:function(url){
	    				App.blockUI($("#tab_1_3"));
	    				console.log("准备提交");
	    			},
	    			successCallback:function(url){
	    				App.unblockUI($("#tab_1_3"));
	    				console.log("操作成功");
	    			},
	    			failCallback: function (html, url) {
	    				rmsBox.notify('error', {msg: '操作失败！',delay:3000});
	    			}
	            });
	  	    	downloadExcel(exportTime+".xlsx");
			})
			
			/**
			 * 轮询检查excel是否生成
			 * @param fileName 文件名
			 */
			function downloadExcel(fileName){
	  	    	var timer = window.setInterval(function(){
		  	    		$.ajax({
							"type" : "post",
							"url" : "main/packDataMonitor/checkExcelTempExist.mvc",
							"dataType" : "json",
							"async" : false,
							"data" : {
								'fileName' : fileName
							},
							"success" : function(resp) {
								if(resp.flag == "success"){
									clearInterval(timer);
									//下载生成文件的文件
									var url = "main/packDataMonitor/downloadTrailExcel.mvc?fileName="+fileName;
						  	    	$.fileDownload(url, {
						    			httpMethod: 'POST',
						    			prepareCallback:function(url){
						    				console.log("准备提交");
						    			},
						    			successCallback:function(url){
						    				rmsBox.notify('success', {msg: '操作成功'});
						    				console.log("操作成功");
						    			},
						    			failCallback: function (html, url) {
						    				rmsBox.notify('error', {msg: '操作失败！',delay:3000});
						    			}
						            });
									
								}
							},
							error:function(e){
							}
						});
				},3000);
	  	    }
			
		},
		/**
		 * 显示监控位置信息
		 * @param c 终端id
		 * @param p 电池id
		 */
		setMonitorLocation:function(c, p){
			 $("#locaion_monitor_box").empty();//清空地图内容
			    var map = new BMap.Map("locaion_monitor_box");
				map.centerAndZoom(new BMap.Point(116.417854,39.921988),14);//默认中心点
				map.enableScrollWheelZoom(true);//缩放
				//向地图中添加缩放控件  
             var ctrlNav = new window.BMap.NavigationControl({  
                 anchor: BMAP_ANCHOR_TOP_LEFT,  
                 type: BMAP_NAVIGATION_CONTROL_LARGE  
             });  
             map.addControl(ctrlNav);
             //向地图中添加缩略图控件  
             var ctrlOve = new window.BMap.OverviewMapControl({  
                 anchor: BMAP_ANCHOR_BOTTOM_RIGHT,  
                 isOpen: 1  
             });  
             map.addControl(ctrlOve);
             //向地图中添加比例尺控件  
             var ctrlSca = new window.BMap.ScaleControl({  
                 anchor: BMAP_ANCHOR_BOTTOM_LEFT  
             });  
             map.addControl(ctrlSca); 
             var myIcon = new BMap.Icon("./media/image/point_icon.png", new BMap.Size(40, 45));  
             //添加标注
 			$.ajax({
				'type':'post',
				'url':'main/packDataMonitor/getCurrentLocationInfo.mvc',
				'dataType':'json',
				"cache":false,
				'async':true,
				'data':{
					'packCode':p,
					'clientId':c},
				'success':function(data){
					//清空上次标注
					map.clearOverlays(); 
					if(data && data.clientId!=null){
							var new_point = new BMap.Point(data.longitude, data.latitude);
							var marker = new BMap.Marker(new_point,{icon:myIcon});  // 创建标注
							var _facName = data.facName;
							_facName = data.facName == null?'未关联厂区':data.facName;
							var lableInfo ="<table><tr><td><b>最后采集时间：</b>"+data.gatherTime+"</td><td><b>采集终端ID：</b>"+data.clientId+"</td></tr>" +
							"<tr><td><b>电池ID：</b>"+data.packCode+"</td><td><b>SOC：</b>" + data.soc + "</td></tr>" +
							"<tr><td><b>总电压：</b>" + data.vol + "V</td><td><b>总电流：</b>" + data.current +"A</td></tr>" +
							"<tr><td><b>客户：</b>" + data.cusName + "</td><td><b>所属厂区：</b>" + _facName + "</td></tr>" +
							"<tr><td><b>地理位置：</b>"+data.address+"</td><td></td></tr>" +
								"</table>"
							var info = new window.BMap.InfoWindow(lableInfo);
							marker.addEventListener("mouseover", function () {
			                        this.openInfoWindow(info);
			                    });
							map.addOverlay(marker);// 将标注添加到地图中
							map.panTo(new_point);
					}
					
				},
				'error':function(msg){
					console.log("error");
				}
			})
		},
		
		/**
		 * 配置echart 绘制电池电压电流图表
		 * @param data 数据
		 * @param elem divID
		 * @param m 峰值配置项目
		 * @param co 颜色列表
		 */
		EconfigAPI:function(data, elem, m, co) {
			//--- 折柱 ---
			//console.log(data);
			var myChart = echarts.init(document.getElementById(elem));
			myChart.setOption({
				tooltip : {
					trigger : 'axis',
					formatter:"{b}<br/>{a} : {c}V"
				},
				calculable : true,
				xAxis : [{
						type : 'category',
						data : data.groupNo
					}
				],
				yAxis : [{
						type : 'value',
						scale : false,
						axisLabel : {
			                formatter: function (data) {
			                    return data.toFixed(3) + ' V'
			                }
			            }
					}
				],
				series : [{
						name : '电压',
						type : 'bar',
						data : (function (){
			                var res = [];
			                for(var i = 0; i< data.vol.length;i++){
			                	res.push(data.vol[i].toFixed(3));
			                }
			                return res;
			            })(),
					    markPoint : {
			                data : m
			            },
			            itemStyle: {
			            	normal: {
			            		color: function(params){
			            			//debugger
			            			//最大值置为红色#E02222 最小值#0D638F 中间值 '#57B5E3'
			            			/*var myData = data.vol;
			            			function compare(value1, value2) { //数字排序的函数参数
										if (value1 < value2) { //小于，返回负数
											return -1;
										} else if (value1 > value2) { //大于，返回正数
											return 1;
										} else { //其他，返回0
											return 0;
										}
									}
									myData.sort(compare);
									if(params.data == myData[myData.length-1]){
										return co[0];
									} else if (params.data == myData[0]){
										return co[1];
									} else {
										return co[2];
									}*/
									if(params.data > data.maxVol){
										return "#E02222";
									}else if(params.data <data.minVol) {
										return "#FFFF00";
									}else {
										return "#57B5E3";
									}
					            }
			            	}
			            }
					}]
			});
		},
		
		//下载报文
		downloadDatagram : function(id) {
			var param = {};
			param['pkId'] = id;
			$.fileDownload("main/packDataMonitor/downloadDatagram.mvc", {
    			httpMethod: 'POST',
    			data: param,
    			prepareCallback:function(url){
    			},
    			successCallback:function(url){
    			},
    			failCallback: function (html, url) {
    				util.showModal("#_alertModal", "未找到指定文件，下载失败！");
    			}
            });
		},
		
		//数据回传
		dataBack : function (id) {
			var param = {};
			param['pkId'] = id;
			//加遮罩
			App.blockUI($("#tab_1_4"));
			$.ajax({
				"type" : "post",
				"url" : "main/packDataMonitor/dataBack.mvc",
				"dataType" : "json",
				"data" : param,
				"success" : function(resp) {
					App.unblockUI($("#tab_1_4"));
					if (resp.msg=='error') {
						rmsBox.notify('error', {msg: '数据异常，回传失败！'});
					} else if (resp.msg=='error dict') {
						rmsBox.notify('error', {msg: '系统相关配置数据错误，请系统管理员！', delay:'2500', width : '400px'});
					} else if (resp.msg=='FILE_EMPTY') {
						rmsBox.notify('error', {msg: '未找到报文文件！', delay:'2500', width : '400px'});
					} else {
						rmsBox.notify('success', {msg: '数据回传成功！'});
						var table = $('#history_warning_table').DataTable();
						table.draw(true);
					}
				},
				error:function(e){
					App.unblockUI($("#tab_1_4"));
					rmsBox.notify('error', {msg: '数据回传失败！'});
				}
			});
		},
		showClientInfoPanel:function(){
		    	$.ajax({
					"type" : "post",
					"url" : "main/sysUser/checkUserClass.mvc",
					"async" : false,
					"dataType":"json",
					"success" : function(resp) {
					    if(resp.flag == "false"){
					    	$("#client_panel_div").show();
					    } else {
					    	$("#client_panel_div").hide();
					    }
					}
		        });
		},
		/**
		 * 
		 * @param id 设置的id
		 * @param count 信号
		 */
		setSign:function(id, count){
			var tmpElement = document.getElementById(id);
			for(var i=0;i<5;i++){
				tmpElement.children[i].style.backgroundColor = "#FFF";
				if(i<=count-1){
					if(count<2){ 
						tmpElement.children[i].style.backgroundColor = "red";//一格时为红色
					}else{
						tmpElement.children[i].style.backgroundColor = "#00ABC5";
					}
				}
			}
		},
		/**
		 * 绘制温度仪表盘
		 * @param divId 温度仪表divId
		 * @param data 数据
		 */
		setTempCanvas:function(divId, tempData){
			var option = {
				    tooltip : {
				        formatter: "{a} <br/>{b} : {c}℃"
				    },
				    toolbox: {
				        show : true,
				        feature : {
				            mark : {show: true}
				        }
				    },
				    series : [
				        {
				        	splitNumber:11,
				        	min:-30,
				        	max:80,
				        	axisLine: {            // 坐标轴线  
			                     lineStyle: {       // 属性lineStyle控制线条样式  
			                         color: [[0.27, '#93C8AC'], [0.82, '#6683A0'], [1, '#C3362F']]
			                                }  
			                            },   
				            name:'监测点最高温度',
				            type:'gauge',
				            detail : {formatter:'{value}℃'},
				            data:[{value: tempData, name: '温度'}]
				        }
				    ]
				};
		    var myChart = echarts.init(document.getElementById(divId));
		    myChart.setOption(option,true);
		},
		
		/**
		 * 绘制电池soc canvas
		 * @param val soc percent
		 */
		setSocCanvas : function(val) {
			var canvas = document.getElementById('canvas'), ctx = canvas
					.getContext('2d');

			var width = 75, height = 20, max = 100;
			// Draw the background
			ctx.fillStyle = '#D2DDEB';
			ctx.clearRect(0, 0, canvas.width, canvas.height);
			ctx.fillRect(0, 0, width, height);
			// Draw the fill
			ctx.fillStyle = '#68CB68';
			var fillVal = Math.min(Math.max(val / max, 0), 1);
			ctx.fillRect(0, 0, fillVal * width, height);
			//添加百分比文字
			ctx.font = "30pt";
			ctx.strokeText(val + "%", 30, 15);
			ctx.strokeStyle = "black";
			ctx.stroke();
			//电池帽子
			ctx.fillStyle = '#D2DDEB';
			ctx.fillRect(75, 5, 6, 9);
		},


		
		/**
		 * 设置电子围栏
		 * @param c 终端ID
		 * @param p 电池id
		 */
		setEfence:function(c, p, t){
			//实例化地图，关闭点击
		    var map = new BMap.Map("e_fence_mapZone", {enableMapClick:false});
		    overlays = [];
		    circleOverlays=[];
		    polygon= null;
		    centerPoints = null;
		    efence_type = t;
		    circle_efence = null;
			$.ajax({
				'type':'post',
				'url':'main/packDataMonitor/getEfenceInfo.mvc',
				'dataType':'json',
				"cache":false,
				'async':false,
				'data':{
					'packCode':p,
					'clientId':c
					},
				'success':function(data){
					map.clearOverlays();
					//设置中心点
					if (data != null && data.locationInfo != null){
						map.centerAndZoom(new BMap.Point(data.locationInfo.longitude, data.locationInfo.latitude), 15);  
						centerPoints = new BMap.Point(data.locationInfo.longitude, data.locationInfo.latitude);
						var myIcon = new BMap.Icon("./media/image/point_icon.png", new BMap.Size(40, 45));  
						var marker = new BMap.Marker(centerPoints,{icon:myIcon});  // 创建标注
						map.addOverlay(marker);// 将标注添加到地图中
					} else {
						map.centerAndZoom(new BMap.Point(116.33556, 39.91588), 15);  
					}
				    map.enableScrollWheelZoom();
				    //添加已有围栏
				    if (data != null && data.fenceInfo != null && data.fenceInfo.gpsInfo.length>0) {
				    		//debugger
				    		//多边形区域
				    		var gps = [];
				    		var gpsInfo = data.fenceInfo.gpsInfo;
				    		//判断电子围栏形状
				    		if(gpsInfo.length==1&&gpsInfo[0].TYPE=='0'){//圆形
				    			if(efence_type == '0'||efence_type == '') {
				    				//圆心
					    			var centerpoint = new BMap.Point(gpsInfo[0].LON,gpsInfo[0].LAT);
					    			circle_efence = new BMap.Circle(centerpoint, gpsInfo[0].RADIUS, {
					    				strokeColor: "blue",
	            						strokeWeight: 2,
	            						fillColor: "#E2E8F1",
	            						fillOpacity: 0.6
					    			});
					    			map.addOverlay(circle_efence);
	        						circle_efence.enableEditing();
	        						circleOverlays.push(circle_efence);
	        						efence_type ='0';
				    			} else {
				    				var pointCenter = map.getCenter();
							        var zoom = map.getZoom();
							    	polygon = new BMap.Polygon([  
							        new BMap.Point(pointCenter.lng - (0.15/zoom), pointCenter.lat - (0.15/zoom)),  
							        new BMap.Point(pointCenter.lng + (0.15/zoom), pointCenter.lat - (0.15/zoom)),  
							        new BMap.Point(pointCenter.lng, pointCenter.lat + (0.15/zoom))  
								    ], {strokeColor:"blue", strokeWeight:2, strokeOpacity:0.5});  //创建多边形  
								    map.addOverlay(polygon);   //增加多边形 
								    polygon.enableEditing();
								    overlays.push(polygon);
								    efence_type = '1';
				    			}
				    			        						
				    		}else {
				    			if(efence_type == '1' || efence_type == '') {
				    				$.each(data.fenceInfo.gpsInfo, function(i, item){
					    				gps.push(new BMap.Point(item.LON, item.LAT))
					    			})
					    			polygon = new BMap.Polygon(gps, {
					    				strokeColor:"blue", 
					    				strokeWeight:2, 
					    				strokeOpacity:0.6
					    			});  //创建多边形  
					    			map.addOverlay(polygon);   //增加多边形 
	                    	    	polygon.enableEditing();
	                    	    	overlays.push(polygon);
	                    	    	efence_type = '1';
				    			} else {
				    				//圆形
					    			var pointCenter = map.getCenter();
						    		map.centerAndZoom(pointCenter, 15); 
						    		circle_efence = new BMap.Circle(pointCenter, 500, {
					    				strokeColor: "blue",
		        						strokeWeight: 2,
		        						fillColor: "#E2E8F1",
		        						fillOpacity: 0.6
						    		});
						    		map.addOverlay(circle_efence);
		        					circle_efence.enableEditing();
		        					circleOverlays.push(circle_efence);
		        					efence_type = '0';
				    			}

				    		}
				    		
				    } else {
				    	//不存在电子围栏信息 默认添加一个三角形的区域
				    	//获取中心点
				    	if(efence_type == '1'||efence_type == '') {
				    		var pointCenter = map.getCenter();
					        var zoom = map.getZoom();
					    	polygon = new BMap.Polygon([  
					        new BMap.Point(pointCenter.lng - (0.15/zoom), pointCenter.lat - (0.15/zoom)),  
					        new BMap.Point(pointCenter.lng + (0.15/zoom), pointCenter.lat - (0.15/zoom)),  
					        new BMap.Point(pointCenter.lng, pointCenter.lat + (0.15/zoom))  
						    ], {strokeColor:"blue", strokeWeight:2, strokeOpacity:0.5});  //创建多边形  
						    map.addOverlay(polygon);   //增加多边形 
						    polygon.enableEditing();
						    overlays.push(polygon);
						    efence_type = '1';
				    	}else {
				    		var pointCenter = map.getCenter();
				    		map.centerAndZoom(pointCenter, 15); 
				    		circle_efence = new BMap.Circle(pointCenter, 500, {
			    				strokeColor: "blue",
        						strokeWeight: 2,
        						fillColor: "#E2E8F1",
        						fillOpacity: 0.6
				    		});
				    		map.addOverlay(circle_efence);
        					circle_efence.enableEditing();
        					circleOverlays.push(circle_efence);
        					efence_type ='0';
				    	}
				        
				    }
				},
				'error':function(msg){
					console.log("error");
				}
			})

			

				    
		    

			
			
			
		}
	};
}();
